import { SimulationConfig } from './simulator';
import { getOSSSimulationConfigFilePath } from './util';
import {objectStorageService} from "./objectStorage";
import {configurationService} from "./configService";


export class SimulationConfigCache {
  private static _simConfig: SimulationConfig;
  private static _inputLabelMap: Map<string, string>;
  private static _outputLabelMap: Map<string, string>;

  private constructor() {
  }

  public static async init() {
    const simConfigPath = getOSSSimulationConfigFilePath();
    try {
      const simConfigString = await objectStorageService.getString(configurationService.config.objectStorage.config.bucket, simConfigPath, 'utf-8');
      if (simConfigString) {
        this._simConfig = JSON.parse(simConfigString);
        this.parseLabel();
      }
    } catch (e) {
      console.warn(`Get Simulation Config File From OSS Error: ${e.message}`);
    }
  }

  public static put(simConfig: SimulationConfig) {
    this._simConfig = simConfig;
    this.parseLabel();
  }

  public static get() {
    return this._simConfig;
  }

  public static inputFulfill(inputs) {
    if (!inputs) {
      return inputs;
    }

    for (let input of inputs) {
      let label = input?.name;
      let name = this._inputLabelMap.get(label);
      if (name) {
        input.name = name;
        input.mdoLabel = label;
      }
    }

    return inputs;
  }

  public static outputFulfill(outputs) {
    if (!outputs) {
      return outputs;
    }

    for (let output of outputs) {
      let label = output?.name;
      let name = this._outputLabelMap.get(label);
      if (name) {
        output.name = name;
        output.mdoLabel = label;
      }
    }

    return outputs;
  }

  private static parseLabel() {
    this._inputLabelMap = new Map();
    this._outputLabelMap = new Map();

    if (this._simConfig?.input) {
      for (const input of this._simConfig?.input) {
        let name = input?.name;
        let label = input?.mdoLabel;
        if (label) {
          this._inputLabelMap.set(label, name);
        }
      }
    }
    
    if (this._simConfig?.output) {
      for (const output of this._simConfig?.output) {
        let name = output?.name;
        let label = output?.mdoLabel;
        if (label) {
          this._outputLabelMap.set(label, name);
        }
      }
    }
    
  }
}
